<template>
    <a-form>
        <a-row>
            <a-col :span="24">
                <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="i18n('mapPane.selSubTable','选择子表')">
                    <a-select v-if="mdl.relationType=='onetomany'" allowClear @change="subTableChange" v-model="mdl.userSubTable" :options="manyOptions" />
                    <a-select v-else allowClear @change="subTableChange" v-model="mdl.userSubTable" :options="mainOptions" />
                </a-form-item>
            </a-col>
        </a-row>
        <a-row>
            <a-col :span="24">
                <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="i18n('mapPane.tableMap','目标表映射')">
                    <div style="height: 400px;padding-right: 10px;">
                        <rx-grid
                            ref="table"
                            :showPage="false"
                            :dataSource="fields"
                            :columns="dataGridColumn"
                            :heightAuto="true"
                            :enableHtmlEscape="false"
                        >
            <span slot="columnType" slot-scope="{text,record}">
                <span v-html="renderDataType(record)"></span>
            </span>
                            <span slot="isNull" slot-scope="{text,record}">
                {{ getIsNullValue(text,isNullMap) }}
            </span>
                            <span slot="mapType" slot-scope="{text,record,index,blur}">
                <a-select labelInValue :options="mapTypes" v-model="record.mapType"
                          @blur="blur(index,'mapType',text,record)"
                          :dropdown-menu-style="{width:'200px'}"
                          :dropdownMatchSelectWidth="false"
                ></a-select>
            </span>
                            <span slot="mapValue" slot-scope="{text,record,index,blur}">
                <a-select v-if="record.mapType=='field' || record.mapType.key=='field'" :options="fieldDatas" v-model="record.mapValue"
                          @blur="blur(index,'mapValue',text,record)"
                          :dropdown-menu-style="{width:'200px'}"
                          :dropdownMatchSelectWidth="false"
                ></a-select>
                <a-select v-if="record.mapType=='mainField' || record.mapType.key=='mainField'" :options="mainFieldDatas" v-model="record.mapValue"
                          @blur="blur(index,'mapValue',text,record)"
                          :dropdown-menu-style="{width:'200px'}"
                          :dropdownMatchSelectWidth="false"
                ></a-select>
                <a-select v-if="record.mapType=='subField' || record.mapType.key=='subField'" :options="subFieldDatas" v-model="record.mapValue"
                          @blur="blur(index,'mapValue',text,record)"
                          :dropdown-menu-style="{width:'200px'}"
                          :dropdownMatchSelectWidth="false"
                          :defaultOpen="true"></a-select>
                <a-input v-if="record.mapType=='fixValue' || record.mapType.key=='fixValue'" v-model="record.mapValue"
                         @blur="blur(index,'mapValue',text,record)"/>
                <rx-input-button v-if="record.mapType=='scriptValue' || record.mapType.key=='scriptValue'" @click="openScript($event,blur,index,record)"
                                 v-model="record.mapValue"></rx-input-button>
                <rx-input-button v-if="record.mapType=='seqValue' || record.mapType.key=='seqValue'" @click="openSeqId($event,blur,index,record)"
                                 v-model="record.mapValue"></rx-input-button>
            </span>
                        </rx-grid>
                    </div>
                </a-form-item>
            </a-col>
        </a-row>
    </a-form>

</template>

<script>
    import FormDbApi from "@/api/form/bo/formDb";
    import FormBoEntityApi from "@/api/form/bo/formBoEntity";
    import {Dialog,RxGrid, RxInputButton, Util} from "@lowcode/jpaas-common-lib"
    import FormSolutionMappingScript from "./FormSolutionMappingScript";
    import FormBoAttrApi from "@/api/form/bo/formBoAttr";

    export default {
        name: "formSolutionMappingPane",
        props: ["conf"],
        components: {
            RxInputButton,
            RxGrid
        },
        computed: {
            table() {
                return this.$refs.table;
            },
        },
        data() {
            return {
                labelCol1: {span: 3},
                wrapperCol1: {span: 19},
                mdl: {
                    userMainTable:'',
                    userSubTable: ''
                },
                mainTable:{},
                subTables:[],
                mainOptions:[],
                manyOptions:[],
                subTablesObj:{},
                fields: [],
                dataGridColumn: [
                    {
                        title: this.$ti18('rxList.index','序号'),
                        type: 'indexColumn',
                        width: 100,
                        dataIndex: 'serial',
                        scopedSlots: {customRender: 'serial'}
                    },
                    {title: this.i18n('form.field','字段'), dataIndex: 'fieldName', width: 100},
                    {title: this.$ti18('rxForm.notes','备注'), dataIndex: 'comment', width: 100},
                    {title: this.i18n('mapPane.dataType','数据类型'), dataIndex: 'columnType', width: 100, scopedSlots: {customRender: 'columnType'}},
                    {title: this.i18n('mapPane.isNull','是否可空'), dataIndex: 'isNull', width: 100, scopedSlots: {customRender: 'isNull'}},
                    {
                        title: this.i18n('form.valueSource','值来源'),
                        dataIndex: 'mapType',
                        displayField: 'mapTypeName',
                        allowCellEdit: true,
                        width: 100,
                        scopedSlots: {customRender: 'mapType'}
                    },
                    {title: this.i18n('mapPane.value','值'), dataIndex: 'mapValue', allowCellEdit: true, width: 100, scopedSlots: {customRender: 'mapValue'}}
                ],
                mapTypes: [{value: 'none', label: this.i18n('mapPaneTypes.none','无')},
                    {value: 'field', label: this.i18n('mapPaneTypes.getFromField','从字段获取')},
                    {value: 'mainField', label: this.i18n('mapPaneTypes.mainField','从主表字段获取')},
                    {value: 'subField', label: this.i18n('mapPaneTypes.subField','从子表字段获取')},
                    {value: 'fixValue', label: this.i18n('mapPaneTypes.fixValue','固定值')},
                    {value: 'scriptValue', label: this.i18n('mapPaneTypes.scriptValue','从脚本函数计算获取')},
                    {value: 'srcPkId', label: this.i18n('mapPaneTypes.srcPkId','源表主键字段值')},
                    {value: 'pkId', label: this.i18n('mapPaneTypes.pkId','由系统产生的主键字段值')},
                    {value: 'mainPkId', label: this.i18n('mapPaneTypes.mainPkId','源主表主键字段值')},
                    {value: 'mainPk', label: this.i18n('mapPaneTypes.mainPk','主表主键字段值(新建表单时使用)')},
                    {value: 'seqValue', label: this.i18n('mapPaneTypes.seqValue','由流水号产生')},
                    {value: 'curDate', label: this.i18n('mapPaneTypes.curDate','获取当前时间')},
                    {value: 'curUserId', label: this.i18n('mapPaneTypes.curUserId','获取当前用户Id')},
                    {value: 'curUserName', label: this.i18n('mapPaneTypes.curUserName','获取当前用户姓名')},
                    {value: 'curDepId', label: this.i18n('mapPaneTypes.curDepId','获取当前部门Id')},
                    {value: 'curDepName', label: this.i18n('mapPaneTypes.curDepName','获取当前部门名称')},
                    {value: 'curInstId', label: this.i18n('mapPaneTypes.curInstId','获取当前机构Id')},
                    {value: 'curInstName', label: this.i18n('mapPaneTypes.curInstName','获取当前机构名称')}],
                fieldDatas: [],
                mainFieldDatas: [],
                subFieldDatas:[],
                boDefId:'',
                boName:'',
                isMain:'',
                isNullMap: {
                    true: this.i18n('mapPane.yes','是'),
                    false: this.i18n('mapPane.no','否')
                }
            }
        },
        filters: {
            isNullFilter(isNull) {
                const isNullMap = {
                    true: '是',
                    false: '否'
                }
                return isNullMap[isNull]
            }
        },
        created() {
            this.loadData();
            this.loadMainEnt();
        },
        methods: {
            i18n(name,text,key){
                return this.$ti18(name,text,"formSolution",key);
            },
            getIsNullValue(key, map){
                return map[key];
            },
            mainTableChange() {
                this.boDefId = '';
                this.boName = '';
                this.isMain = '';
                this.mainFieldDatas = [];
                this.fieldDatas = [];
                this.boName = this.mainTable.boName;
                this.boDefId = this.mainTable.boDefId;
                this.isMain = this.mainTable.isMain;
                this.subTables = this.subTablesObj[this.boDefId];
                this.mainOptions=this.subTables?this.subTables.filter(item=>item.relationType=='onetoone'):[];
                this.manyOptions=this.subTables?this.subTables.filter(item=>item.relationType=='onetomany'):[];
                this.loadBoAttrs("mainFieldDatas", this.boDefId, "_main", true, true);
                this.loadBoAttrs("fieldDatas", this.boDefId, this.boName, true, true);
            },
            subTableChange(value){
                if(!value){
                    this.subFieldDatas=[];
                    return;
                }
                var boName;
                for(var i=0;i<this.subTables.length;i++){
                    if(this.subTables[i].value==value){
                        boName=this.subTables[i].alias;
                    }
                }
                this.loadBoAttrs("subFieldDatas", this.boDefId, boName, true, true);
            },
            loadMainEnt(){
                var self_=this;
                FormBoAttrApi.queryToBoEntity(this.mdl.boDefId).then(res => {
                    self_.subTables=[];
                    for(var i=0;i<res.length;i++){
                        var boDefId=res[i].boRelation.bodefId;
                        if(res[i].boRelation.type=='main'){
                            var boName=res[i].alias;
                            var isMain=res[i].isMain;
                            self_.mdl.userMainTable=res[i].alias;
                            self_.mainTable={value:res[i].alias,label:res[i].name,boName:boName,boDefId:boDefId,isMain:isMain};
                        }else{
                            if(self_.subTablesObj[boDefId]){
                                self_.subTablesObj[boDefId].push({value:res[i].id,label:res[i].name,alias:res[i].alias,relationType:res[i].boRelation.type});
                            }else{
                                self_.subTablesObj[boDefId]=[{value:res[i].id,label:res[i].name,alias:res[i].alias,relationType:res[i].boRelation.type}];
                            }
                        }
                    }
                    self_.mainTableChange();
                    if(self_.mdl.userSubTable){
                        self_.subTableChange(self_.mdl.userSubTable);
                    }
                });
            },
            renderDataType(record) {
                var val = record.columnType;
                if (val == "varchar") {
                    return val + "(" + record.charLen + ")";
                } else if (val == "number") {
                    if (record.decimalLen == 0) {
                        return val + "(" + record.intLen + ")";
                    } else {
                        return val + "(" + record.intLen + "," + record.decimalLen + ")"
                    }
                }
                return val;
            },
            loadBoAttrs(comboxId, boDefId, entName, needCommonFields, showName) {
                var self = this;
                FormBoEntityApi.getFieldByBoDefId(boDefId, entName).then(data => {
                    data = data.map(item => {
                        return {label: item.comment, value: item.name, isSingle: item.isSingle, control: item.control}
                    })
                    if (!showName) {
                        self[comboxId] = data;
                    } else {
                        for (var i = 0; i < data.length; i++) {
                            var item = data[i];
                            if (item.isSingle == 0) {
                                var field=item.value;
                                item.value=field+"-value";
                                var nameObj = {};
                                nameObj.value = field + "-label";
                                nameObj.label = item.label + "("+self.$ti18('rxForm.name','名称')+")";
                                self[comboxId].push(nameObj);
                            }
                            self[comboxId].push(item);
                        }
                    }
                    if (needCommonFields) {
                        self[comboxId].push(...[
                            {"value": "ID_", "label": self.$ti18('rxForm.ID','主键')},
                            {"value": "REF_ID_", "label": self.i18n('mapPane.assField','关联字段')},
                            {"value": "INST_ID_", "label": self.i18n('mapPane.instId','流程实例ID')},
                            {"value": "PARENT_ID_", "label": self.i18n('mapPane.parentId','父ID')},
                            {"value": "INST_STATUS_", "label": self.i18n('mapPane.instStatus','流程实例状态')},
                            {"value": "CREATE_BY_", "label": self.$ti18('rxForm.createBy','创建人')},
                            {"value": "CREATE_TIME_", "label": self.$ti18('rxForm.createTime','创建时间')},
                            {"value": "UPDATE_BY_", "label": self.$ti18('rxForm.updateBy','更新人')},
                            {"value": "UPDATE_TIME_", "label": self.$ti18('rxForm.updateTime','更新时间')},
                            {"value": "TENANT_ID_", "label": self.i18n('mapPane.tenantId','租户ID')},
                            {"value": "CREATE_DEP_ID_", "label": self.i18n('mapPane.deptId','部门ID')}
                        ])
                    }
                })
            },
            loadData() {
                Object.assign(this.mdl, this.conf);
                if (this.conf.gridData) {
                    this.fields = this.conf.gridData;
                } else {
                    FormDbApi.getByName("dsName=" + this.mdl.dsName + "&tbName=" + this.mdl.tableName).then(data => {
                        var list = data.columnList;
                        this.fields = this.parseFields(list);
                    })
                }
                delete this.mdl.gridData;
            },
            parseFields(list){
                for(var i=0;i<list.length;i++){
                    list[i].mapType='';
                    list[i].mapValue='';
                }
                return list;
            },
            getData() {
                return {
                    ...this.mdl,
                    gridData: this.table.getData()
                }
            },
            openSeqId(vm, blur, index, record) {
                Dialog.openSysSeqIdDialog({
                    curVm: this, widthHeight: ['1300px', '600px']
                }, function (self, data) {
                    vm.setVal(data.alias, data.name);
                    record.mapValue = data.alias;
                    blur(index, 'mapValue', data.alias, record)
                })
            },
            openScript(vm, blur, index, record) {
                var self = this;
                var boName;
                for(var i=0;i<this.subTables.length;i++){
                    if(this.subTables[i].value==this.mdl.userSubTable){
                        boName=this.subTables[i].alias;
                    }
                }
                var baseConf = {
                    "curVm": self,
                    component: FormSolutionMappingScript,
                    title: self.i18n('mapScript.title','设置字段映射'),
                    widthHeight: ['1200px', '700px'],
                    data: {
                        value: record.mapValue,
                        fieldName: record.fieldName,
                        boDefId: self.boDefId,
                        isMain: self.isMain,
                        entName: boName
                    }
                };
                Util.open(baseConf, function (action, data) {
                    if (action == 'ok') {
                        record.mapValue = data;
                    }
                    blur(index, 'mapValue', data, record)
                });
            }
        }
    }
</script>

<style scoped>

</style>
